#!/usr/bin/env ruby

require 'optparse'
require File.join(File.dirname(__FILE__), '../Spec/vectors', 'vectorparser')

@test_files = ["v3/kdf", "v3/password", "v3/key", 
               "v2/kdf", "v2/password",
               "v1/kdf", "v1/password",
              ]

@options = {}

# Returns the text for an NSDictionary assignment from a hash
def NSDictionaryForHash(hash)
  "@{\n" + hash.collect { |key, value| %Q(    @"#{key}": @"#{value}") }.join(",\n") + "}"
end

# Output the file header to output stream
def outputHeader(output)
  output << <<-HEADER
// Automatically Generated by GenVectorTests
#import "XCTestCase+RNCryptorVectorTests.h"
@interface RNCryptorGeneratedVectorTests : XCTestCase
@end
@implementation RNCryptorGeneratedVectorTests
HEADER
end

# Output the tests for a given filename to the output stream
def outputTestsForFile(output, name)
  name_identifier = name.gsub('/', '_')
  VectorParser.new(@options[:vector_directory] + '/' + name).vectors.each do |vector|
    output << <<-TEST_CASE

- (void)test_#{name_identifier}_#{vector["title"].gsub(/[ ()-]+/, '_')} {
  [self verify_#{name_identifier}:#{NSDictionaryForHash(vector)}];
}

TEST_CASE

  end
end

# Output the footer to the output stream
def outputFooter(output)
    output<< <<-FOOTER
@end
FOOTER
end

###################
### MAIN
###################
opt_parser = OptionParser.new do |opt|
  opt.banner = "Usage: GenVectorTest -o VectorTests.m <vector_directory>"
  opt.separator  ""
  opt.on("-o","--output PATH","path to output code") do |output_path|
    @options[:output_path] = output_path
  end
  opt.on("-3", "-3 PATH", "path to v3 directory") do |v3_directory|
    @options[:v3_directory] = v3_directory
  end
end

opt_parser.parse!

raise OptionParser::MissingArgument if @options[:output_path].nil?
raise OptionParser::MissingArgument if ARGV.length != 1

@options[:vector_directory] = ARGV[0]

File.open(@options[:output_path], "w") do |output|
  outputHeader(output)
  @test_files.each do |file|
    outputTestsForFile(output, file)
  end
  outputFooter(output)
end
